<template>
  <view class="container">
    <!-- 日历卡片组件 -->
    <CalendarCard />

    <!-- 摸鱼周报组件 -->
    <WeeklyReportCard />

    <!-- 活跃度卡片组件 -->
    <ActivityCard :activity-data="activityData" @refresh-liveness="refreshLiveness" />

    <!-- 昨日活跃奖励卡片组件 -->
    <RewardCard :show-reward-card="showRewardCard" :reward-received="rewardReceived"
      @update:reward-received="rewardReceived = $event" />

    <!-- 功能入口区域组件 -->
    <FeatureGrid :features="features" />

    <!-- 最新帖子区域组件 -->
    <ArticleList @navigate-to-article="navigateToArticleDetail" @navigate-to-articles="navigateToArticles" />

    <!-- 版本更新弹窗 -->
    <UpdateModal :visible="showUpdateModal" :version-info="versionInfo" :download-status="updateDownloadStatus"
      :download-progress="updateDownloadProgress" @download="handleStartDownload" @install="handleInstallUpdate"
      @cancel="handleUpdateCancel" />
  </view>
</template>

<script setup>
  import { ref, onMounted, onUnmounted } from "vue";
  import { onShow } from "@dcloudio/uni-app";
  import api from "@/api";
  import { isLoggedIn } from "@/api/request";
  import activityUtils from "@/utils/activityUtils.js";
  import { getLatestVersion, compareVersions } from "@/api/version";
  import { getAppVersion } from "@/config/app";

  // 导入组件
  import CalendarCard from "@/components/CalendarCard.vue";
  import WeeklyReportCard from "@/components/WeeklyReportCard.vue";
  import ActivityCard from "@/components/ActivityCard.vue";
  import RewardCard from "@/components/RewardCard.vue";
  import FeatureGrid from "@/components/FeatureGrid.vue";
  import ArticleList from "@/components/ArticleList.vue";
  import UpdateModal from "@/components/UpdateModal.vue";
  import updateUtils from "@/utils/updateUtils";

  // 活跃度相关
  const activityData = ref(activityUtils.getActivityData());
  // 使用 activityUtils 的监听器更新活跃度数据
  let activityUnsubscribe = null;

  // 活跃奖励相关数据
  const showRewardCard = ref(false);
  const rewardReceived = ref(false);

  // 更新相关
  const showUpdateModal = ref(false);
  const versionInfo = ref({});
  const updateDownloadStatus = ref("not_started");
  const updateDownloadProgress = ref(0);

  // 功能入口数据
  const features = ref([
    {
      icon: "file-text",
      name: "帖子",
      url: "/pages/article/list",
    },
    {
      icon: "message-square",
      name: "聊天",
      url: "/pages/chat/message-list",
    },
    {
      icon: "wind",
      name: "清风明月",
      url: "/pages/breezemoon/breezemoon",
    },
    {
      icon: "coffee",
      name: "鱼游",
      url: "/pages/webview/webview?url=" + encodeURIComponent("https://fishpi.cn/activities"),
    },
  ]);

  // 检查昨日活跃奖励状态
  const checkRewardStatus = async () => {
    if (!isLoggedIn()) {
      showRewardCard.value = false;
      return;
    }

    try {
      const res = await api.activity.checkRewardStatus();

      if (res.isCollectedYesterdayLivenessReward === false) {
        showRewardCard.value = true;
        rewardReceived.value = res.isCollectedYesterdayLivenessReward === true;
      }
    } catch (error) {
      console.error("检查奖励状态失败", error);
    }
  };

  // 开始下载更新
  const handleStartDownload = () => {
    updateUtils.startDownload();
  };

  // 安装更新
  const handleInstallUpdate = () => {
    updateUtils.installUpdate();
    showUpdateModal.value = false;
  };

  // 取消更新
  const handleUpdateCancel = () => {
    showUpdateModal.value = false;
  };

  // 初始化更新检测模块
  const initUpdateCheck = () => {
    // 设置更新回调
    updateUtils.setCallbacks({
      onUpdateAvailable: (info) => {
        // 发现新版本时直接显示弹窗
        showUpdateModal.value = true;
        versionInfo.value = info;
        updateDownloadStatus.value = "not_started";
      },
      onDownloadStart: () => {
        updateDownloadStatus.value = "downloading";
        updateDownloadProgress.value = 0;
      },
      onDownloadProgress: (data) => {
        updateDownloadProgress.value = data.progress;
      },
      onDownloadComplete: (filePath, error) => {
        if (filePath) {
          updateDownloadStatus.value = "completed";
          // 如果当前显示着更新弹窗，则保持显示
          if (showUpdateModal.value) {
            versionInfo.value = updateUtils.versionInfo;
          }
        } else {
          updateDownloadStatus.value = "not_started";
          uni.showToast({
            title: "下载更新失败，请重试",
            icon: "none",
          });
        }
      },
    });

    // 自动检查更新
    updateUtils.checkUpdate();
  };

  // 跳转到文章详情页
  const navigateToArticleDetail = (articleId) => {
    uni.navigateTo({
      url: `/pages/article/detail?id=${articleId}`,
    });
  };

  // 跳转到文章列表页
  const navigateToArticles = () => {
    uni.switchTab({
      url: "/pages/article/list",
    });
  };

  // 手动刷新活跃度
  const refreshLiveness = () => {
    activityUtils.refreshLiveness();
  };

  // 页面加载
  onMounted(() => {
    // 添加活跃度变化监听器
    activityUnsubscribe = activityUtils.addListener((data) => {
      activityData.value = data;
    });

    // 初始化活跃度数据
    if (isLoggedIn()) {
      activityUtils.initialize(); // 初始化活跃度数据（包含签到状态检查）
      checkRewardStatus(); // 检查昨日活跃奖励状态
    }

    // 自动检查更新
    initUpdateCheck();
  });

  // 每次页面显示时检查登录状态，更新数据
  onShow(() => {
    if (isLoggedIn()) {
      // 使用活跃度工具类更新数据
      activityUtils.initialize();

      // 检查昨日活跃奖励状态
      checkRewardStatus();
    }
  });

  // 组件销毁时移除事件监听和清除缓存
  onUnmounted(() => {
    // 移除活跃度监听器
    if (activityUnsubscribe) {
      activityUnsubscribe();
    }

    // 清理活跃度相关资源
    activityUtils.cleanup();
  });
</script>

<style lang="scss">
  .container {
    padding-top: 60rpx;
    padding-bottom: 30rpx;
    background-color: #f6f7f9;
    min-height: 100vh;
  }
</style>